import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Image,
  ScrollView,
  Dimensions,
  SafeAreaView,
  ActivityIndicator,
  Animated,
  Alert,
  Modal,
  PanResponder,
} from 'react-native';
import CheckBox from '@react-native-community/checkbox';
import ReactNativeBiometrics from 'react-native-biometrics';
import { wp, hp } from '../utils/layout';
import { FONT_SIZES } from '../utils/fontSize';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { saveTokens, clearTokens } from '../utils/authRequest';

declare module 'react-native-slide-verify';

const { height: SCREEN_HEIGHT } = Dimensions.get('window');
const rnBiometrics = new ReactNativeBiometrics();

const AccountLoginScreen = ({ navigation }: any) => {
  const [account, setAccount] = useState('');
  const [password, setPassword] = useState('');
  const [showPwd, setShowPwd] = useState(false);
  const [checked, setChecked] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [buttonScale] = useState(new Animated.Value(1));
  const [isBiometricAvailable, setIsBiometricAvailable] = useState(false);
  const [accountError, setAccountError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [inputFocus, setInputFocus] = useState({
    account: false,
    password: false,
  });
  const [rememberMe, setRememberMe] = useState(false);
  const [showSlider, setShowSlider] = useState(false);
  const [sliderPassed, setSliderPassed] = useState(false);
  const [sliderX] = useState(new Animated.Value(0));
  const SLIDER_WIDTH = 280;
  const SLIDER_HEIGHT = 40;
  const SLIDER_BTN_SIZE = 36;

  useEffect(() => {
    checkBiometricSupport();
    loadSavedCredentials();
  }, []);

  useEffect(() => {
    if (account && rememberMe) {
      passwordInputRef.current?.focus?.();
    }
  }, [account, rememberMe]);

  const checkBiometricSupport = async () => {
    try {
      const { available, biometryType } = await rnBiometrics.isSensorAvailable();
      setIsBiometricAvailable(available);
    } catch (error) {
      console.log('Biometric check failed:', error);
    }
  };

  const loadSavedCredentials = async () => {
    try {
      const savedAccount = await AsyncStorage.getItem('savedAccount');
      const savedPassword = await AsyncStorage.getItem('savedPassword');
      const savedRememberMe = await AsyncStorage.getItem('rememberMe');

      if (savedAccount && savedPassword && savedRememberMe === 'true') {
        setAccount(savedAccount);
        setPassword(savedPassword);
        setRememberMe(true);
      }
    } catch (error) {
      console.log('Error loading saved credentials:', error);
    }
  };

  const saveCredentials = async () => {
    try {
      if (rememberMe) {
        await AsyncStorage.setItem('savedAccount', account);
        await AsyncStorage.setItem('savedPassword', password);
        await AsyncStorage.setItem('rememberMe', 'true');
      } else {
        await AsyncStorage.removeItem('savedAccount');
        await AsyncStorage.removeItem('savedPassword');
        await AsyncStorage.removeItem('rememberMe');
      }
    } catch (error) {
      console.log('Error saving credentials:', error);
    }
  };

  const handleBiometricLogin = async () => {
    try {
      const { success } = await rnBiometrics.simplePrompt({
        promptMessage: '请使用生物识别登录',
        cancelButtonText: '取消',
      });

      if (success) {
        setIsLoading(true);
        // 模拟登录请求
        setTimeout(() => {
          setIsLoading(false);
          navigation.replace('MainTabs');
        }, 1500);
      }
    } catch (error) {
      Alert.alert('错误', '生物识别失败，请重试');
    }
  };

  const validateInputs = () => {
    let isValid = true;
    
    if (!account) {
      setAccountError('请输入账号');
      isValid = false;
    } else {
      setAccountError('');
    }

    if (!password) {
      setPasswordError('请输入密码');
      isValid = false;
    } else if (password.length < 6) {
      setPasswordError('密码长度不能少于6位');
      isValid = false;
    } else {
      setPasswordError('');
    }

    return isValid;
  };

  const handleAccountChange = (text: string) => {
    if (/^1[3-9]\d{9}$/.test(text.replace(/\s/g, ''))) {
      setAccount(text.replace(/\s/g, ''));
    } else {
      setAccount(text.trim().toLowerCase());
    }
    setAccountError('');
  };

  const passwordInputRef = React.useRef<TextInput>(null);

  const handleLogin = async () => {
    if (!validateInputs()) {
      return;
    }
    Animated.sequence([
      Animated.timing(buttonScale, {
        toValue: 0.95,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.timing(buttonScale, {
        toValue: 1,
        duration: 100,
        useNativeDriver: true,
      }),
    ]).start();
    setIsLoading(true);
    try {
      // 如果密码为空，则使用默认密码 '123456'
      const loginPassword = password || '123456';
      // 登录请求
      const response = await fetch('http://172.20.10.6:3000/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ account, password: loginPassword })
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.message || '登录失败');
      // 保存token
      await saveTokens(data.accessToken, data.refreshToken);
      if (rememberMe) {
        await saveCredentials();
      }
      await AsyncStorage.setItem('userInfo', JSON.stringify(data.user));
      navigation.replace('MainTabs');
    } catch (error: any) {
      const msg = error.message || '登录失败，请重试';
      if (msg.includes('账号')) {
        setAccountError(msg);
      } else if (msg.includes('密码')) {
        setPasswordError(msg);
      } else {
        Alert.alert('错误', msg);
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleLoginPress = () => {
    if (!validateInputs()) return;
    setShowSlider(true); // 弹出滑块
  };

  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onMoveShouldSetPanResponder: () => true,
    onPanResponderMove: (evt, gestureState) => {
      let x = Math.max(0, Math.min(gestureState.dx, SLIDER_WIDTH - SLIDER_BTN_SIZE));
      sliderX.setValue(x);
    },
    onPanResponderRelease: (evt, gestureState) => {
      if (gestureState.dx > SLIDER_WIDTH - SLIDER_BTN_SIZE - 5) {
        // 滑动到最右侧
        Animated.timing(sliderX, {
          toValue: SLIDER_WIDTH - SLIDER_BTN_SIZE,
          duration: 100,
          useNativeDriver: false,
        }).start(() => {
          setShowSlider(false);
          setSliderPassed(true);
          sliderX.setValue(0);
          handleLogin();
        });
      } else {
        // 未滑到最右，回到起点
        Animated.timing(sliderX, {
          toValue: 0,
          duration: 200,
          useNativeDriver: false,
        }).start();
      }
    },
  });

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        style={styles.flex1}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <View style={styles.container}>
          {/* 顶部栏 */}
          <View style={styles.header}>
            <TouchableOpacity onPress={() => navigation.navigate('MainTabs')}>
              <Text style={styles.close}>×</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => navigation.navigate('Register')}>
              <Text style={styles.register}>注册</Text>
            </TouchableOpacity>
          </View>
          <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
            {/* 标题 */}
            <Text style={styles.title}>账号密码登录</Text>
            <Text style={styles.subtitle}>使用已注册账号登录</Text>
            {/* 账号输入 */}
            <View style={[
              styles.inputBox,
              inputFocus.account && styles.inputBoxFocused,
              accountError && styles.inputBoxError
            ]}>
              <Image source={{ uri: 'https://img.icons8.com/ios-filled/50/user-male-circle.png' }} style={styles.inputIconImg} />
              <TextInput
                style={[styles.input, { fontSize: FONT_SIZES.xs }]}
                placeholder="手机号/邮箱/用户名"
                placeholderTextColor="#bbb"
                value={account}
                onChangeText={handleAccountChange}
                onFocus={() => setInputFocus(prev => ({ ...prev, account: true }))}
                onBlur={() => setInputFocus(prev => ({ ...prev, account: false }))}
                autoCapitalize="none"
              />
            </View>
            {accountError ? <Text style={styles.errorText}>{accountError}</Text> : null}
            {/* 密码输入 */}
            <View style={[
              styles.inputBox,
              inputFocus.password && styles.inputBoxFocused,
              passwordError && styles.inputBoxError
            ]}>
              <Image source={{ uri: 'https://img.icons8.com/fluency/48/lock-2.png' }} style={styles.inputIconImg} />
              <TextInput
                ref={passwordInputRef}
                style={[styles.input, { flex: 1, fontSize: FONT_SIZES.xs }]}
                placeholder="请输入密码"
                placeholderTextColor="#bbb"
                value={password}
                onChangeText={(text) => {
                  setPassword(text);
                  setPasswordError('');
                  if (text.length >= 6) {
                    setChecked(true);
                  }
                }}
                onFocus={() => setInputFocus(prev => ({ ...prev, password: true }))}
                onBlur={() => setInputFocus(prev => ({ ...prev, password: false }))}
                secureTextEntry={!showPwd}
                autoCapitalize="none"
              />
              <TouchableOpacity onPress={() => setShowPwd(!showPwd)}>
                <Image 
                  source={{ uri: showPwd ? 'https://img.icons8.com/ios-filled/50/visible--v1.png' : 'https://img.icons8.com/ios-filled/50/closed-eye.png' }} 
                  style={styles.eyeIcon} 
                />
              </TouchableOpacity>
            </View>
            {passwordError ? <Text style={styles.errorText}>{passwordError}</Text> : null}
            {/* 忘记密码 */}
            <TouchableOpacity style={styles.forgotPwd} onPress={() => navigation.navigate('ForgotPassword')}>
              <Text style={styles.forgotPwdText}>忘记密码</Text>
            </TouchableOpacity>
            {/* 记住密码选项 */}
            <View style={styles.rememberMeBox}>
              <CheckBox
                value={rememberMe}
                onValueChange={setRememberMe}
                boxType="square"
                tintColors={{ true: '#1976ff', false: '#bbb' }}
              />
              <Text style={styles.rememberMeText}>记住密码</Text>
            </View>
            {/* 登录按钮 */}
            <Animated.View style={[styles.loginBtnContainer, { transform: [{ scale: buttonScale }] }]}>
              <TouchableOpacity 
                style={[styles.loginBtn, isLoading && styles.loginBtnDisabled]} 
                onPress={handleLoginPress}
                disabled={isLoading}
              >
                {isLoading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={styles.loginBtnText}>登录</Text>
                )}
              </TouchableOpacity>
            </Animated.View>
            {/* 用手机验证码登录 */}
            <TouchableOpacity style={styles.phoneLogin} onPress={() => navigation.replace('PhoneLogin')}>
              <Text style={styles.phoneLoginText}>用手机验证码登录</Text>
            </TouchableOpacity>
            {/* 分割线和快速登录 */}
            <View style={styles.dividerBox}>
              <View style={styles.divider} />
              <Text style={styles.quickLoginTitle}>快速登录</Text>
              <View style={styles.divider} />
            </View>
            <View style={styles.quickLoginBox}>
              <TouchableOpacity style={styles.quickIconBox}>
                <Image source={{ uri: 'https://img.icons8.com/color/48/000000/weixing.png' }} style={styles.quickIcon} />
              </TouchableOpacity>
              <TouchableOpacity style={styles.quickIconBox}>
                <Image source={{ uri: 'https://img.icons8.com/ios-filled/50/000000/mac-os.png' }} style={styles.quickIcon} />
              </TouchableOpacity>
            </View>
            {/* 生物识别登录按钮 */}
            {isBiometricAvailable && (
              <TouchableOpacity 
                style={styles.biometricBtn}
                onPress={handleBiometricLogin}
                disabled={isLoading}
              >
                <Image 
                  source={{ uri: 'https://img.icons8.com/ios-filled/50/fingerprint.png' }} 
                  style={styles.biometricIcon} 
                />
                <Text style={styles.biometricText}>生物识别登录</Text>
              </TouchableOpacity>
            )}
          </ScrollView>
          {/* 协议勾选 固定底部 */}
          <View style={styles.protocolBox}>
            <CheckBox value={checked} onValueChange={setChecked} boxType="square" tintColors={{ true: '#1976ff', false: '#bbb' }} />
            <Text style={styles.protocolText}>
              我已阅读并同意《中国移动认证服务条款》和AI智能医疗辅助系统 用户协议、隐私政策 以及儿童个人信息保护政策
            </Text>
          </View>
          {/* 自定义滑块验证 Modal */}
          <Modal
            visible={showSlider}
            transparent
            animationType="fade"
            onRequestClose={() => setShowSlider(false)}
          >
            <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'center', alignItems: 'center' }}>
              <View style={{ backgroundColor: '#fff', padding: 20, borderRadius: 8, alignItems: 'center' }}>
                <Text style={{ marginBottom: 16, fontSize: 16, textAlign: 'center' }}>请按住滑块，拖动到最右边</Text>
                <View style={{ width: SLIDER_WIDTH, height: SLIDER_HEIGHT, backgroundColor: '#f0f0f0', borderRadius: 20, justifyContent: 'center' }}>
                  <Animated.View
                    {...panResponder.panHandlers}
                    style={{
                      position: 'absolute',
                      left: sliderX,
                      width: SLIDER_BTN_SIZE,
                      height: SLIDER_BTN_SIZE,
                      borderRadius: SLIDER_BTN_SIZE / 2,
                      backgroundColor: '#1976ff',
                      justifyContent: 'center',
                      alignItems: 'center',
                      zIndex: 2,
                      elevation: 2,
                    }}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 18 }}>{'>>'}</Text>
                  </Animated.View>
                  <View style={{ position: 'absolute', left: 0, top: 0, width: SLIDER_WIDTH, height: SLIDER_HEIGHT, justifyContent: 'center', alignItems: 'center' }}>
                    <Text style={{ color: '#888' }}>拖动滑块完成验证</Text>
                  </View>
                </View>
                <TouchableOpacity onPress={() => setShowSlider(false)} style={{ marginTop: 16 }}>
                  <Text style={{ color: '#1976ff', textAlign: 'center' }}>取消</Text>
                </TouchableOpacity>
              </View>
            </View>
          </Modal>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
  },
  flex1: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingHorizontal: 24,
    paddingTop: 40,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 0,
    height: 40,
  },
  close: {
    fontSize: 28,
    color: '#222',
    fontWeight: 'bold',
  },
  register: {
    fontSize: 16,
    color: '#1976ff',
    fontWeight: 'bold',
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: 'flex-start',
    minHeight: 0,
    paddingTop: 0,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#222',
    textAlign: 'center',
    marginTop: 60,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 14,
    color: '#888',
    textAlign: 'center',
    marginBottom: 32,
  },
  inputBox: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f6fa',
    borderRadius: 24,
    paddingHorizontal: 16,
    marginBottom: 20,
    height: 48,
    width: '100%',
  },
  inputIconImg: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
    marginRight: 8,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: '#222',
    minWidth: 0,
  },
  eyeIcon: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
    marginLeft: 8,
  },
  forgotPwd: {
    alignSelf: 'flex-end',
    marginBottom: 0,
    marginTop: -12,
  },
  forgotPwdText: {
    color: '#1976ff',
    fontSize: 14,
    textAlign: 'center',
  },
  loginBtnContainer: {
    width: '100%',
    marginBottom: 32,
    marginTop: 0,
  },
  loginBtn: {
    backgroundColor: '#1976ff',
    borderRadius: 24,
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  loginBtnDisabled: {
    opacity: 0.8,
  },
  loginBtnText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  phoneLogin: {
    alignSelf: 'center',
    marginBottom: 24,
  },
  phoneLoginText: {
    color: '#1976ff',
    fontSize: 14,
    textAlign: 'center',
  },
  dividerBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 24,
    width: '100%',
  },
  divider: {
    flex: 1,
    height: 1,
    backgroundColor: '#eee',
  },
  quickLoginTitle: {
    color: '#888',
    fontSize: 14,
    marginHorizontal: 8,
    textAlign: 'left',
  },
  quickLoginBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 24,
  },
  quickIconBox: {
    marginHorizontal: 16,
    backgroundColor: '#f5f6fa',
    borderRadius: 32,
    padding: 12,
  },
  quickIcon: {
    width: 40,
    height: 40,
    resizeMode: 'contain',
  },
  protocolBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 24,
    marginTop: 'auto',
    paddingHorizontal: 0,
  },
  protocolText: {
    fontSize: 12,
    color: '#bbb',
    marginLeft: 8,
    flex: 1,
    lineHeight: 18,
  },
  errorText: {
    color: '#ff4d4f',
    fontSize: 12,
    marginTop: -12,
    marginBottom: 12,
    marginLeft: 16,
  },
  rememberMeBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  rememberMeText: {
    fontSize: 14,
    color: '#666',
    marginLeft: 8,
  },
  inputBoxFocused: {
    borderWidth: 1,
    borderColor: '#1976ff',
    backgroundColor: '#fff',
  },
  inputBoxError: {
    borderWidth: 1,
    borderColor: '#ff4d4f',
    backgroundColor: '#fff',
  },
  biometricBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#f5f6fa',
    borderRadius: 24,
    padding: 12,
    marginBottom: 20,
  },
  biometricIcon: {
    width: 20,
    height: 20,
    marginRight: 8,
  },
  biometricText: {
    color: '#1976ff',
    fontSize: 16,
  },
});

export default AccountLoginScreen; 